#pragma once
#include <iostream>
#include <string>
#include "log.hpp"
#include "Init.hpp"
using namespace std;

Log log;
Init init;

class Task
{
public:
    Task(const int &socketFd, const string &ip, const uint16_t &port) 
    : _socketFd(socketFd), _ip(ip), _port(port)
    {}

    void Run()
    {
        // 每个线程得到结果后就让它退出
        char buf[1024];
        // 从socketFd中读取数据
        ssize_t n = read(_socketFd, buf, sizeof (buf) - 1);
        if(n > 0) {
            buf[n] = 0;          // 确保字符串以空字符结尾
            // 写回客户端
            string echoString = "server get a message$ ";
            echoString += init.translation(buf);
            printf("client say$ %s\n", buf);
            n = write(_socketFd, echoString.c_str(), echoString.size());
            if(n == -1) {
                log(WARNING, "向客户端 %s:%d 发送信息失败, 关闭fd: %d\n", _ip.c_str(), _port, _socketFd);
            }
        } else if(n == 0) {
            log(INFO, "客户端 %s:%d 退出, 关闭fd: %d\n", _ip.c_str(), _port, _socketFd);
        } else {
            log(WARNING, "读取客户端 %s:%d 信息失败, 关闭fd: %d\n", _ip.c_str(), _port, _socketFd);
        }
        close(_socketFd);       // 注意这里不要忘记close()
    }
private:
    int _socketFd;
    string _ip;
    uint16_t _port;
};